package com.dzt.cloudreader.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dzt.cloudreader.CloudReaderApp;
import com.dzt.cloudreader.R;
import com.dzt.cloudreader.adapter.MovieDetailAdapter;
import com.dzt.cloudreader.base.HeaderActivity;
import com.dzt.cloudreader.model.HotMovieBean.SubjectsBean;
import com.dzt.cloudreader.model.MovieDetailBean;
import com.dzt.cloudreader.model.PersonBean;
import com.dzt.cloudreader.network.MovieDetailPresenter;
import com.dzt.cloudreader.network.MovieDetailView;
import com.dzt.cloudreader.utils.JLogKit;
import com.dzt.cloudreader.utils.JStringFormatKit;
import com.dzt.cloudreader.webview.WebViewActivity;
import com.dzt.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import jp.wasabeef.glide.transformations.BlurTransformation;

public class OneMovieDetailActivity extends HeaderActivity {
    @BindView(R.id.tv_one_day)
    TextView tvOneDay;
    @BindView(R.id.tv_one_city)
    TextView tvOneCity;
    @BindView(R.id.tv_one_rating_rate)
    TextView tvOneRatingRate;
    @BindView(R.id.tv_one_rating_number)
    TextView tvOneRatingNumber;
    @BindView(R.id.tv_one_directors)
    TextView tvOneDirectors;
    @BindView(R.id.tv_one_casts)
    TextView tvOneCasts;
    @BindView(R.id.tv_one_genres)
    TextView tvOneGenres;
    @BindView(R.id.img_item_bg)
    ImageView ivItembg;
    @BindView(R.id.tv_summary)
    TextView tvSummary;
    @BindView(R.id.tv_one_title)
    TextView tvOneTitle;
    @BindView(R.id.xrv_cast)
    XRecyclerView recyclerView;
    private MovieDetailAdapter adapter;
    private List<PersonBean> lists = new ArrayList<>();
    private MovieDetailPresenter presenter;
    private SubjectsBean subjectsBean;
    private String mMoreUrl;
    private String mMovieName;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_one_movie_detail;
    }

    @Override
    protected void initParams() {
        if (getIntent() != null) {
            subjectsBean = (SubjectsBean) getIntent().getSerializableExtra("bean");
        }
        presenter = new MovieDetailPresenter(context);
        presenter.onCreate();
        presenter.attachView(detailView);

        initSlideShapeTheme(setHeaderImgUrl(), setHeaderImageView());

        setTitle(subjectsBean.getTitle());
        setSubTitle(String.format("主演：%s", JStringFormatKit.formatPerson(subjectsBean.getCasts())));
        tvOneRatingRate.setText(getString(R.string.string_rating) + subjectsBean.getRating().getAverage());
        tvOneRatingNumber.setText(subjectsBean.getCollect_count() + getString(R.string.string_rating_num));
        tvOneDirectors.setText(JStringFormatKit.formatPerson(subjectsBean.getDirectors()));
        tvOneCasts.setText(JStringFormatKit.formatPerson(subjectsBean.getCasts()));
        tvOneGenres.setText(JStringFormatKit.formatGenres(subjectsBean.getGenres()));

        loadMovieDetail();
    }

    @Override
    protected void setTitleClickMore() {
        WebViewActivity.loadUrl(OneMovieDetailActivity.this, mMoreUrl, mMovieName);
    }

    @Override
    protected int setHeaderLayout() {
        return R.layout.header_slide_shape;
    }

    @Override
    protected String setHeaderImgUrl() {
        if (subjectsBean == null) {
            return "";
        }
        return subjectsBean.getImages().getMedium();
    }

    @Override
    protected ImageView setHeaderImageView() {
        return ivItembg;
    }

    private void loadMovieDetail() {
        JLogKit.getInstance().e("id = " + subjectsBean.getId());
        presenter.getMovieDetail(subjectsBean.getId());
    }

    /**
     * 异步线程转换数据
     */
    private void transformData(final MovieDetailBean movieDetailBean) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < movieDetailBean.getDirectors().size(); i++) {
                    movieDetailBean.getDirectors().get(i).setType("导演");
                }
                for (int i = 0; i < movieDetailBean.getCasts().size(); i++) {
                    movieDetailBean.getCasts().get(i).setType("演员");
                }

                OneMovieDetailActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setAdapter(movieDetailBean);
                    }
                });
            }
        }).start();
    }

    /**
     * 设置导演&演员adapter
     */
    private void setAdapter(MovieDetailBean movieDetailBean) {
        recyclerView.setVisibility(View.VISIBLE);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(OneMovieDetailActivity.this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setPullRefreshEnabled(false);
        recyclerView.setLoadingMoreEnabled(false);
        // 需加，不然滑动不流畅
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setHasFixedSize(false);
        for (PersonBean person : movieDetailBean.getDirectors()) {
            lists.add(person);
        }
        for (PersonBean person : movieDetailBean.getCasts()) {
            lists.add(person);
        }
        adapter = new MovieDetailAdapter(context, lists, R.layout.item_movie_detail_person);
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void onRefresh() {
        loadMovieDetail();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
    }

    private MovieDetailView detailView = new MovieDetailView() {
        @Override
        public void onSuccess(MovieDetailBean movie) {
            showContentView();
            // 上映日期
            tvOneDay.setText(String.format("上映日期：%s", movie.getYear()));
            // 制片国家
            tvOneCity.setText(String.format("制片国家/地区：%s", JStringFormatKit.formatGenres(movie.getCountries())));
            ImageView ivOnePhoto = headerView.findViewById(R.id.iv_one_photo);
            Glide.with(context).load(movie.getImages().getLarge())
                    .crossFade(500)
                    .error(R.mipmap.img_default_movie)
                    .into(ivOnePhoto);

            Glide.with(context).load(movie.getImages().getMedium())
                    .crossFade(500)
                    .bitmapTransform(new BlurTransformation(context, 23, 4))
                    .placeholder(R.mipmap.stackblur_default)
                    .error(R.mipmap.stackblur_default)
                    .into(ivItembg);

            mMoreUrl = movie.getAlt();
            mMovieName = movie.getTitle();

            tvOneTitle.setText(JStringFormatKit.formatGenres(movie.getAka()));
            tvSummary.setText(movie.getSummary());

            transformData(movie);
        }

        @Override
        public void onError(String result) {

        }
    };

    /**
     * @param context      activity
     * @param positionData bean
     * @param imageView    imageView
     */
    public static void start(Activity context, SubjectsBean positionData, ImageView imageView) {
        JLogKit.getInstance().i("start " + positionData.toString());
        Intent intent = new Intent(context, OneMovieDetailActivity.class);
        intent.putExtra("bean", positionData);
        ActivityOptionsCompat options =
                ActivityOptionsCompat.makeSceneTransitionAnimation(context,
                        imageView, CloudReaderApp.getInstance().getResources().getString(R.string.transition_movie_img));//与xml文件对应

        ActivityCompat.startActivity(context, intent, options.toBundle());
    }
}
